-- 集群操作封装接口
-- auth:diandian
-- date:2018/9/27
--

local skynet = require "skynet.manager"
local cluster = require "skynet.cluster"
local ex_log = require "ex_log"

local _nodemap = {}
local _typemap = {}
local _listen = false
local M = {}


function M.start_center(host)
    cluster_center = skynet.newservice("ex_cluster_center")
    return skynet.call(".ex_cluster_center", "lua", "start", host)
end

function M.start_node(...)
    local svr = skynet.localname(".ex_cluster_node")
    if not svr then
        svr = skynet.newservice("ex_cluster_node")
        ex_log.info("new ex_cluster_node:", svr)
    end
    return skynet.call(svr, "lua", "start", ...)
end

local function gen_typemap()
    _typemap = {}
    for k, v in pairs(_nodemap) do
        local map = _typemap[v.type]
        if not map then
            map = {}
            _typemap[v.type] = map
        end
        map[k] = v
    end
end

function M.enabled(time)
    time = time or 200
    local function update_clusters()
        skynet.timeout(time, update_clusters)
        local nodemap = skynet.call(".ex_cluster_node", "lua", "get_info")
        _nodemap = nodemap
        gen_typemap()
    end
    update_clusters()
end

function M.get_map()
    return _nodemap
end



function M.get_types(type_)
    return _typemap[type_]
end

function M.call(...)
    return cluster.call(...)
end

function M.call_node(node, ...)
    return cluster.call(node.name, node.svr, ...)
end

function M.send(...)
    return cluster.send(...)
end

function M.send_node(node, ...)
    cluster.send(node.name, node.svr, ...)
end

function M.call_center(...)
    return cluster.call("center_node", ...)
end

function M.send_center(...)
    return cluster.send("center_node", ...)
end

return M
